const uuid = require("uuid");

const inintSocket = (app) => {
  const server = require('http').createServer(app.callback());
  const io = require('socket.io')(server,{
    allowEIO3: true,    // 兼容v2版本的socket.io客户端，兼容小程序weapp.socket.io(基于socket.io2.x)
    cors: true //解决跨域问题
  });

  //中间件注册
  io.use((socket, next) => {
    // if (isValid(socket.request)) {
    //   next();
    // } else {
    //   next(new Error("invalid"));
    // }
    // console.log("中间件函数",socket.handshake);
    console.log("执行socket中间件函数");
    next()
  });

  io.on('connection', socket => { 
    console.log("socket链接成功");

    //连接人数
    console.log("socket连接人数",io.engine.clientsCount);

    //加入房间
    socket.on("join room",(room) => {
      socket.join(room)
      io.to("room:1").emit("join group",`${socket.id}加入房间`)
    })

    //发送群聊
    socket.on("group chat",(msg) => {
      io.to("room:1").emit("send msg",msg)
    })
    
    //断开连接触发
    socket.on("disconnect", (reason) => {
      console.log(socket.id,"断开连接");
    });

  });

  //链接关闭时候出现什么
  io.engine.on("connection_error", (err) => {
    console.log(err.req);      // the request object
    console.log(err.code);     // the error code, for example 1
    console.log(err.message);  // the error message, for example "Session ID unknown"
    console.log(err.context);  // some additional error context
  });



  server.listen(9999);
}

module.exports = inintSocket